<?php

/*
 * 命令行生成证书
 * @since 1.0 <2015-7-20> SoChishun Added.
 * @example php /var/lib/asterisk/bin/cert.php
 */
header("Content-Type:text/html; charset=UTF-8");
// 接收参数
// IP
fwrite(STDOUT, "IP: ");
$param['ip'] = trim(fgets(STDIN));
if (!$param['ip']) {
    echo 'IP INVALID!', PHP_EOL;
    exit;
}
// 最大用户数
fwrite(STDOUT, "AGENT: ");
$param['agent'] = trim(fgets(STDIN));
if ($param['agent'] && !is_numeric($param['agent'])) {
    echo 'AGENT INVALID!', PHP_EOL;
    exit;
}
// 最大外呼数
fwrite(STDOUT, "TRUNK: ");
$param['trunk'] = trim(fgets(STDIN));
if ($param['trunk'] && !is_numeric($param['trunk'])) {
    echo 'TRUNK INVALID!', PHP_EOL;
    exit;
}
// 过期时间
fwrite(STDOUT, "EXPIRE: ");
$param['expires_time'] = trim(fgets(STDIN));

// 默认值
if (!$param['ip']) {
    $param['ip'] = $_SERVER['SERVER_NAME'];
}
$param['username'] = $param['ip'];
if (!$param['agent']) {
    $param['agent'] = '600';
}
if (!$param['trunk']) {
    $param['trunk'] = '3000';
}
if (!$param['expires_time']) {
    $param['expires_time'] = '3000-1-1 0:0:0';
}

// 确认信息
echo 'Infomation:', PHP_EOL;
var_export($param);
echo PHP_EOL;
fwrite(STDOUT, 'Please type [y|n] to continue:');
$confirm = trim(fgets(STDIN));
if (!$confirm || 'y' != strtolower($confirm)) {
    echo 'Operate cancel.', PHP_EOL;
    exit;
}

// 加密
$content = '';
foreach ($param as $key => $value) {
    $content.=",$key=$value";
}
$content = substr($content, 1);
$content = encrypt_rnd($content);
$content = '??' . str_replace('==', '??', $content);

// 生成文件
$dir = '/var/www/html/xcallsqzs/Licence/';
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}
file_put_contents($dir . 'licence.txt', $content);

echo "SUCCESS:)", PHP_EOL;

/**
 * @since 1.0 2014-10-15 by sutroon
 */
function encrypt_rnd($data, $mode = 'ENCRYPT', $key = 'xcallEncrypt!@#') {
    if ($mode == 'ENCRYPT') {
        srand((double) microtime() * 1000000);
        $rand = rand(1, 10000);
        $encrypt_key = md5($rand);
        $ctr = 0;
        $tmp = '';
        for ($i = 0; $i < strlen($data); $i++) {
            $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
            $tmp .= $encrypt_key[$ctr] . ($data[$i] ^ $encrypt_key[$ctr++]);
        }
        $tmp = encrypt_rnd_key($tmp, $key);
        return base64_encode($tmp);
    }
    if ($mode == 'DENCRYPT') {
        $txt = base64_decode($data);
        $txt = encrypt_rnd_key($txt, $key);
        $tmp = '';
        for ($i = 0; $i < strlen($txt); $i++) {
            $md5 = $txt[$i];
            $tmp .= $txt[++$i] ^ $md5;
        }
        return $tmp;
    }
    return $data;
}

/**
 * @since 1.0 2014-10-15 by sutroon
 */
function encrypt_rnd_key($data, $key) {
    $ctr = 0;
    $tmp = '';
    for ($i = 0; $i < strlen($data); $i++) {
        $ctr = $ctr == strlen($key) ? 0 : $ctr;
        $tmp .= $data[$i] ^ $key[$ctr++];
    }
    return $tmp;
}
?> 

